<?php

namespace app\index\controller;

use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Request;
use think\Session;
use think\Validate;
use tree\Tree;

class Index extends Controller
{

    /************ AI萌宝数字人对接接口模块 ***********/

    /**
     * 提交语音
     * */
    public function submitVoice()
    {
        if ($_FILES['file']) {
            $file = $_FILES['file']['tmp_name'];

            $access_token = get_access_token('ai_access_token.json', 1);
            if (!$access_token) apiReturn(2, '获取access_token失败');

            $voice_id = uniqid() . time();

            $curlFile = new \CURLFile($file, 'audio/mp3', 'voice.mp3');

            $url = "https://api.weixin.qq.com/cgi-bin/media/voice/addvoicetorecofortext?access_token=$access_token&format=mp3&voice_id=$voice_id&lang=zh_CN";

            $res = $this->httpPost($url, $curlFile);
            if ($res) {
                $data = json_decode($res, true);
                if ($data['errcode'] == 0) {
                    apiReturn(1, '上传成功', $voice_id);
                }
            } else {
                apiReturn(2, '上传失败');
            }
        } else {
            apiReturn(2, '请上传语音');
        }
    }

    /**
     * 语音识别
     * */
    public function voiceRecognition()
    {
        $input = Request()->param();

        $voice_id = $input['voice_id'];
        if (!$voice_id) apiReturn(2, '语音id为空');

        $access_token = get_access_token('ai_access_token.json', 1);
        if (!$access_token) apiReturn(2, '获取access_token失败');

        $url = "https://api.weixin.qq.com/cgi-bin/media/voice/queryrecoresultfortext?access_token=$access_token&voice_id=$voice_id&lang=zh_CN";
        $res = $this->httpCurl($url);
        if ($res) {
            $data = json_decode($res, true);
            apiReturn(1, '获取数据成功', $data);
        } else {
            apiReturn(2, '获取数据失败');
        }
    }


    // 公共 POST 请求方法
    public function httpPost($url, $postData)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);

        // 使用 multipart/form-data
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: multipart/form-data']);
        curl_setopt($ch, CURLOPT_POSTFIELDS, ['media' => $postData]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $output = curl_exec($ch);
        curl_close($ch);

        return json_decode($output, true);
    }

    /**
     * @param $url
     * @param $data
     * @return mixed|false
     */
    public function httpCurl($url, $data = null, $header = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        // 设置连接超时时间（单位：秒）
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60); // 60 秒
        // 设置请求超时时间（单位：秒）
        curl_setopt($curl, CURLOPT_TIMEOUT, 120);       // 120 秒
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        // 设置header头
        if (!empty($header)) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        $response = curl_exec($curl);
        if ($response === false) {
            // 处理 CURL 请求失败的情况
            echo 'CURL Error: ' . curl_error($curl);
            return false;
        } else {
            // 请求成功，返回 API 响应数据
            return $response;
        }

        curl_close($curl);
    }
    /************ AI萌宝数字人对接接口模块 ***********/
}
